package com.lab.es.demo.aspect;


import com.lab.es.demo.annotation.TimeHandle;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Aspect
@Component
@Order(100)
public class TimeAspect {

    @Pointcut("@annotation(com.lab.es.demo.annotation.TimeHandle)")
    public void annotationPoinCut() {
    }

    @Around(value = "annotationPoinCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        TimeHandle timeHandle = method.getAnnotation(TimeHandle.class);

        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            log.info("around 参数=" + arg + " ");
        }

        log.info(timeHandle.desc() + " doAround-1:" + new SimpleDateFormat("yyyyMMdd hh:mm:ss").format(new Date()));
        Object obj = joinPoint.proceed();
        log.info(timeHandle.desc() + " doAround-2 返回值:" + obj);
        log.info(timeHandle.desc() + " doAround-3:" + new SimpleDateFormat("yyyyMMdd hh:mm:ss").format(new Date()));
        return obj;
    }

    @Before(value = "annotationPoinCut()")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        TimeHandle timeHandle = method.getAnnotation(TimeHandle.class);
        log.info(timeHandle.desc() + " before:" + new SimpleDateFormat("yyyyMMdd hh:mm:ss").format(new Date()));
    }

    @After(value = "annotationPoinCut()")
    public void after(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        TimeHandle timeHandle = method.getAnnotation(TimeHandle.class);
        log.info(timeHandle.desc() + " after:" + new SimpleDateFormat("yyyyMMdd hh:mm:ss").format(new Date()));
    }

    @AfterReturning(value = "annotationPoinCut()", returning = "returnValue")
    public void afterReturning(JoinPoint joinPoint, Object returnValue) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        TimeHandle timeHandle = method.getAnnotation(TimeHandle.class);
        log.info(timeHandle.desc() + " afterReturning: 返回值: " + returnValue);
    }
}
